# -*- coding: utf-8 -*-
"""
Created on Mon Nov 11 09:05:33 2013

@author: Magda
"""
import stockdata
from bottle import route, run, template, request
import pandas
import datetime

@route('/crawl')
def index():
    company_name = request.query.company
    start_date = request.query.start_date_name
    end_date = request.query.end_date_name

    print "Company: " + company_name
    company_name = str.upper(company_name.encode('ascii','ignore'))
    valid_company = check_company(company_name)

    print "Start date: " + start_date
    print "End date: " + end_date

    tuples = []
    stock = 0 # TODO: Should be "" ?
    min_val = 0
    max_val = 0
    if(len(start_date) > 0 and valid_company):
		sd = stockdata.StockData()
		
        start_date_object = datetime.datetime.strptime(start_date, "%m/%d/%Y")
        end_date_object = datetime.datetime.strptime(end_date, "%m/%d/%Y")
        stock_data = sd.get_stock_data(company_name, start_date_object.date(), end_date_object.date())        
        stock_data = stock_data[company_name].dropna(how='all')
        stock = stock_data[company_name][0]
        min_val = stock_data[company_name].min()
        max_val = stock_data[company_name].max()
        tuples = [tuple(x) for x in stock_data.to_records(index=True)]
        # TODO: Instantiate a stocknews object
        #articles = stocknews.StockNews(stock?, start_date, end_date)
        # TODO: Load classifier from file
        #from sklearn.externals import joblib
        #classifier = joblib.load(open("filename"))
        # TODO: Classify articles
        #vectorizer = TfidfVectorizer(max_features=MAX_FEATURES, stop_words='english')
        #X_test = vectorizer.transform([article for article in articles.iterate('content')])
        #classifications = classifier.predict(X_test)
        #dates = [article for article in articles.iterate('datetime')]
        # TODO: Count negative and positive
        # make pandas dataframe, use group_by on the data column and sum on condition 'positive'


    return template('magda_template', company=company_name, stock=stock, invalid=str(not(valid_company)), start=start_date, end=end_date, data=tuples, minval=min_val, maxval=max_val)

def check_company(name):
    companies = pandas.read_csv("http://www.student.dtu.dk/~s110848/companylist.csv")
    return len(companies[companies.keys()[0]][companies[companies.keys()[0]] == name]) > 0


run(host='localhost', port=8080)

"""todo:
    - companies from combo box in which you can write
    + start and end date working
    + displaying the stock value for a given timespan
    + ploting the stock values
    - resizing of textarea
    - getting the text and testing in by use of a classifier
    - to conclusion: 
        set of recommended words in articles
    """